using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Forecast.Business;
using Forecast.Database;
using System.Text;

public partial class Prediction : System.Web.UI.Page
{
    Forecast.Database.Prediction _prediction;
    Forecast.Database.Load _load;
    Forecast.Business.Activity _activity;

    protected void Page_Load(object sender, EventArgs e)
    {
        _topNews.TopNewsVisibilityChanged += new TopNewsVisibilityChangedEventHandler(_topNews_TopNewsVisibilityChanged);
        _activeOffers.ActiveOffersChanged += new ActiveOffersChangedEventHandler(_activeOffers_ActiveOffersChanged);        
        if (string.IsNullOrEmpty(Request["id"])) throw new Exception("Missing argument - don't know what prediction to display.");
        _load = new Forecast.Database.Load(ConfigurationManager.ConnectionStrings["ForecastDB"].ConnectionString);
        _activity = new Activity(ConfigurationManager.ConnectionStrings["ForecastDB"].ConnectionString);

        if (!IsPostBack)
        {
            BindData();
        }
    }

    void _topNews_TopNewsVisibilityChanged(object sender, EventArgs e)
    {
        BindData();
    }

    private void BindData()
    {
        _prediction = _load.GetPrediction(Int32.Parse(Request["id"]));
        Title = "The Forecast Exchange - " + _prediction.Ticker;        

        _header.Text = string.Format("<b>{0}</b> : {1}<br/>",
            _prediction.Ticker,
            _prediction.ShortDescription);


        _subHead.Text = string.Format("{0}: {1}<br/>",
            _prediction.IsActive ? "<b>End date</b>" : "<b>Ended</b>",
            _prediction.EndDate.ToLongDateString());
        if (_prediction.IsActive)
            _subHead.ToolTip = "This is the last possible date for this prediction to end. It could end earlier if the success or failure criteria are met. No trading is allowed after the prediction has been closed.";

        _longDescription.Text = "<b>Description:</b><br/>";
        _longDescription.Text += StringExtensions.RenderAsHtml(_prediction.LongDescription);

        _predictionResults.Visible = false;
        if (_prediction.IsActive)
        {
            _status.Text = "<b>Last:</b> " + _prediction.LastValue;
            _status.Text += "<br />";
            _status.Text += "<b>Last change:</b> " + GetLastChange();
            _status.Text += "<br />";
            int numStocksForSale = _activity.GetNumStocksForSaleForPlayer(UserHelper.GetUserId(Page.User.Identity.Name), _prediction.Id);
            if (numStocksForSale == 0)
                _status.Text += "<b>You currently own " + GetNumStocks() + " stocks. </b>";
            else
                _status.Text += "<b>You currently own " + GetNumStocks() + " stocks, of which " + numStocksForSale.ToString() + " are for sale. </b>";
        }
        else
        {
            if (_prediction.IsClosed)
            {
                _predictionResults.Visible = true;
                _predictionResults.BindData(_prediction.Id);
                if (_prediction.HasSucceeded)
                    _status.Text = "<b>This prediction succeeded.</b>";
                else
                    _status.Text = "<b>This prediction failed.</b>";
            }
            else
                _status.Text = "<b>This prediction has not yet been activated.</b>";
        }

        _activeOffers.BindData(_prediction.Id);

        if (_activeOffers.HasAnyActiveOffers())
        {
            _upperCreateNewOfferLink.Visible = true;
            _upperCreateNewOfferLink.Align = "right";
            _lowerCreateNewOfferLink.Align = "right";
        }
        else
        {
            _upperCreateNewOfferLink.Visible = false;
            _upperCreateNewOfferLink.Align = "left";
            _lowerCreateNewOfferLink.Align = "left";
        }
        
        _topNews.BindData(_prediction);
    }

    protected string GetCreateNewOfferSentence()
    {
        if (_prediction.IsClosed || _prediction.EndDate < DateTime.Today)
            return "";
        return string.Format("<a href=\"CreateOffer.aspx?id={0}\">Create a new offer on {1}</a>", _prediction.Id, _prediction.Ticker);
    }

    protected string GetTicker()
    {
        return _prediction.Ticker;
    }

    protected string GetLastValue()
    {
        return _prediction.LastValue.ToString();
    }

    protected string GetLastChange()
    {
        return string.Format("<span style=\"color:{0};\">{1}{2}%</span>",
            (_prediction.LastChange >= 0 ? "green" : "red"),
            (_prediction.LastChange >= 0 ? "+" : ""),
            _prediction.LastChange);
    }

    protected string GetNumStocks()
    {
        Activity activity = new Activity(ConfigurationManager.ConnectionStrings["ForecastDB"].ConnectionString);
        int numStocksForSale = activity.GetNumStocksForSaleForPlayer(UserHelper.GetUserId(Page.User.Identity.Name), _prediction.Id);
        Player player = _load.GetPlayer(UserHelper.GetUserId(Page.User.Identity.Name));
        Holding holding = _load.GetHolding(player, _prediction);
        int numStocks = holding.NumPredictions + numStocksForSale;

        if (holding == null)
            return "0";
        else
            return numStocks.ToString();

    }

    protected string GetOffers()
    {
        Activity activity = new Activity(ConfigurationManager.ConnectionStrings["ForecastDB"].ConnectionString);
        int[] trades = activity.GetAllTrades(_prediction);
        StringBuilder offersString = new StringBuilder();
        for (int i = 0; i < trades.Length; i++)
        {
            offersString.AppendFormat("{0},", trades[i]);
        }

        return offersString.Length > 0 ? 
            offersString.ToString().Substring(0, offersString.Length -1) :
            string.Empty;
    }

    void _activeOffers_ActiveOffersChanged(object sender, EventArgs e)
    {
        BindData();
    }

}
